
const WebSocket = require('ws');

;((Ws) => {

  const server = new Ws.Server({ port:8000 })

  const init = () => {
    bindEvent()
  }
  
  function bindEvent () {
    server.on('open', handleOpen, false);
    server.on('close', handleClose, false);
    server.on('error', handleError, false);
    server.on('connection', handleConnection, false);
  }

  function handleOpen(e) {
    console.log('open', e);
  }

  function handleClose(e) {
    console.log('close',e);
  }

  function handleError(e) {
    console.log('errorwwwww',e);
  }

  function handleConnection(ws) {
    console.log('connection');

    ws.on('message', handleMessage, false)
  }

  function handleMessage(msg) {
    console.log(String(msg));

    server.clients.forEach(item => {
      item.send(String(msg))
    })
    
  }

  init()
})(WebSocket);